package uade.distribuidas.server.dao;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import uade.distribuidas.repo.exception.ExceptionOrdenCompra;
import uade.distribuidas.server.domain.OrdenCompra;
import uade.distribuidas.server.hibernate.HibernateUtil;

public class OrdenesCompraDAO {

	private static OrdenesCompraDAO instancia = null;
	private static SessionFactory sf = null;

	public static OrdenesCompraDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new OrdenesCompraDAO();
		} 
		return instancia;
	}
	
	@SuppressWarnings("unchecked")
	public List<OrdenCompra> getCompras() throws ExceptionOrdenCompra{
		Session session = sf.openSession();
		
		List<OrdenCompra> lista = session.createQuery("from OrdenCompra").list();		
	
		
		session.close();
		return lista;
	}
	

	public OrdenCompra getCompra(Integer id)throws ExceptionOrdenCompra{
		Session session = sf.openSession();
		
		OrdenCompra c = (OrdenCompra) session.createQuery("from OrdenCompra where id = :id")
				.setParameter("id", id)
				.uniqueResult();			
		
		session.close();
		return c;
	}

	public OrdenCompra save(OrdenCompra c) throws ExceptionOrdenCompra{
		Session session = sf.openSession();
		 Transaction transaction = session.beginTransaction();
		 transaction.begin();
		 session.saveOrUpdate(c);
		 transaction.commit();
		 session.close();
		 return c;
	}
	

}
